package com.example.micro.netty.server.buf;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class NettyByteBufDemo2 {

    public static void main(String[] args) {

        //创建ByteBuf
        ByteBuf byteBuf = Unpooled.copiedBuffer("hello world!", StandardCharsets.UTF_8);

        //使用相关的方法
        if (byteBuf.hasArray()) {

            byte[] content = byteBuf.array();

            //将content装成字符串
            System.out.println(new String(content, StandardCharsets.UTF_8));

            System.out.println("byteBuf=" + byteBuf);

            System.out.println(byteBuf.arrayOffset());//0
            System.out.println(byteBuf.readerIndex());//0
            System.out.println(byteBuf.writerIndex());//12
            System.out.println(byteBuf.capacity());//36 因为1个字符，36个字节

            int len = byteBuf.readableBytes();//可读的字符数  12
            System.out.println("可读的字符数：" + len);

            //输出各个字符
            for (int i = 0; i < len; i++) {
                System.out.print((char) byteBuf.getByte(i));
            }
            System.out.println();

            //分段取字符 从0开始 读4个
            System.out.println(byteBuf.getCharSequence(0, 4, StandardCharsets.UTF_8));

        }

    }

}
